#include <Arduino.h>
#include <WebSocketsServer.h>
#include <NTPClient.h>
#define USE_SERIAL Serial
WebSocketsServer webSocket = WebSocketsServer(83);

long client_num=-1;
int websocket_ntp_second;
extern NTPClient timeClient;
extern String read_state();


void webSocketEvent(uint8_t num, WStype_t type, uint8_t *payload, size_t length)
{

    switch (type)
    {
    case WStype_DISCONNECTED:
    {
        USE_SERIAL.printf("[%u] Disconnected!\n", num);
        client_num = -1;
    }

    break;
    case WStype_CONNECTED:
    {
        IPAddress ip = webSocket.remoteIP(num);
        USE_SERIAL.printf("[%u] Connected from %d.%d.%d.%d url: %s\n", num, ip[0], ip[1], ip[2], ip[3], payload);
        client_num = num;
    }
    break;
    case WStype_TEXT:
        USE_SERIAL.printf("[%u] get Text: %s\n", num, payload);
        break;
    case WStype_BIN:
        USE_SERIAL.printf("[%u] get binary length: %u\n", num, length);
        //hexdump(payload, length);
        break;
    }
}

void websocket_setup()
{
    webSocket.begin();
    webSocket.onEvent(webSocketEvent);
}

void websocket_loop()
{
    webSocket.loop();
    if (timeClient.getSeconds() != websocket_ntp_second)
    {
        String state = read_state();
        //Serial.print("\n state ");
        //Serial.print(state);
        webSocket.sendTXT(client_num, state);
        websocket_ntp_second=timeClient.getSeconds();
    }
}
